package com.example.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.enums.RoleEnum;
import com.example.common.exception.ServiceException;
import com.example.entity.Account;
import com.example.mapper.AccountMapper;
import com.example.service.IAccountService;
import com.example.vo.req.LoginReqVO;
import com.example.vo.req.RegisterReqVO;
import com.example.vo.resp.AuthorizeRespVO;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hbin
 * @since 2025-01-04
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAccountService {

    @Override
    public void doRegister(RegisterReqVO requestParam) {
        String username = requestParam.getUsername();
        String password = requestParam.getPassword();
        if (existsUsername(username)) throw new ServiceException("该用户名已被使用！");
        String encrypt = BCrypt.hashpw(password, BCrypt.gensalt());
        Account account = new Account(null, username, encrypt, RoleEnum.user.getRole(), new Date());
        if (!save(account)) throw new ServiceException("内部错误，注册失败！");
    }

    @Override
    public AuthorizeRespVO doLogin(LoginReqVO requestParam) {
        String username = requestParam.getUsername();
        String password = requestParam.getPassword();
        Account account = query().eq("username", username).one();
        if (Objects.isNull(account)) throw new ServiceException("用户名不存在！");
        if (!BCrypt.checkpw(password, account.getPassword())) throw new ServiceException("密码不正确！");
        StpUtil.login(account.getId());
        return new AuthorizeRespVO(username, StpUtil.getTokenValue(), account.getRole());
    }

    private boolean existsUsername(String username) {
        return exists(Wrappers.<Account>query().eq("username", username));
    }
}
